import { useIntl } from '@umijs/max';
import { Spin } from 'antd';
import ReactEcharts from 'echarts-for-react';
import React, { useEffect, useRef, useState } from 'react';

interface Ipros {
  chartData: API.DeviceExtremeDTO[];
  moduleType: string;
}
export const BarChart: React.FC<Ipros> = ({ chartData, moduleType }) => {
  const [loading, setLoading] = useState(true);
  const [isEmpty, setEmpty] = useState(true);
  const [pageData, setPageData] = useState<API.DeviceExtremeDTO>({});
  const chartRef = useRef(null);
  const intl = useIntl();
  // const colors = ['#1a6cfe', '#ff7f0e'];

  useEffect(() => {
    chartRef?.current?.getEchartsInstance()?.resize();
  });

  useEffect(() => {
    if (chartData && chartData?.length) {
      chartRef?.current?.getEchartsInstance()?.clear();
      setLoading(false);
      setPageData(chartData);
      setEmpty(false);
    } else {
      chartRef?.current?.getEchartsInstance()?.clear();
      setLoading(false);
      setPageData(chartData);
      setEmpty(true);
    }
  }, [chartData]);

  const changeXdata = (data) => {
    let arr = [];
    if (data && data?.length) {
      arr = data?.map((item) => item.deviceName);
    }

    return arr;
  };

  const changeData = (
    AllData: API.DeviceExtremeDTO[],
    itemdata: number | undefined,
    index: number,
  ) => {
    let arr = [];
    arr = AllData?.map((item, selfIndex) => {
      if (selfIndex === index) {
        return itemdata;
      } else {
        return null;
      }
    });
    return arr;
    //  console.log(arr,"相应的")
  };

  const changeSeriesData = (data: API.DeviceExtremeDTO[]) => {
    let arr: any = [];
    if (data && data?.length) {
      arr = data?.map((item, index) => {
        return {
          type: 'bar',
          name: item?.deviceName,
          data: changeData(data, item?.avg, index), //
          itemStyle: {
            color: '#1A6CFE', //
          },
          barwidth: '30%',
          barGap: '-100%', // Overlap bars
        };
      });
    }

    return arr;
  };

  const changeName = (moduleType: string) => {
    if (moduleType === 'tempt') {
      return `${intl.formatMessage({ id: 'stationRealtimeMonitoring.Temperature' })}`;
    } else if (moduleType === 'vol') {
      return intl.formatMessage({ id: 'stationRealtimeMonitoring.Voltage' });
    }
  };

  // changeUnit

  const changeUnit = (moduleType: string) => {
    if (moduleType === 'tempt') {
      return `℃`;
    } else if (moduleType === 'vol') {
      return `V`;
    }
  };

  return (
    <div style={{ width: '100%', height: 240 }}>
      <Spin spinning={loading}>
        <ReactEcharts
          ref={chartRef}
          style={{ width: '100%', height: 240 }}
          option={{
            tooltip: {
              trigger: 'axis',
              show: !isEmpty,
              formatter: function (params) {
                let text = `<div>`;
                const otherName = changeName(moduleType);
                const unit = changeUnit(moduleType);
                params.forEach((item) => {
                  if (item?.value) {
                    const value = item.value;
                    text += `${item.marker}${item.seriesName}</br>${otherName}&nbsp;:&nbsp;&nbsp;${value}${unit}<br/><br/>`;
                  }
                });
                text += '</div>';
                return text;
              },
            },
            dataZoom: [
              {
                type: 'inside', // 内置型数据区域缩放组件
                start: 0, // 默认起始位置为 0%
                end: 100, // 默认结束位置为 100%
              },
            ],
            legend: {
              right: 0,
              top: 0,
              show: false,
            },

            grid: {
              left: 40,
              right: 5,
              top: 40,
              bottom: 15,
              containLabel: true,
              show: true,
              borderColor: 'transparent',
              backgroundColor: isEmpty ? 'transparent' : '#F8F9FA',
            },
            xAxis: [
              {
                type: 'category',
                name: false,
                nameTextStyle: {
                  //y轴上方单位的颜色
                  color: '#222',
                },
                data: changeXdata(pageData),
                axisTick: {
                  alignWithLabel: true,
                  show: true,
                  inside: true, //刻度内置
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisLabel: {
                  color: '#222',
                },
              },
            ],
            yAxis: [
              {
                type: 'value',
                nameTextStyle: {
                  color: '#222',
                  align: 'left',
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisTick: {
                  show: true,
                  inside: true,
                },
                splitLine: {
                  show: !isEmpty,
                  lineStyle: {
                    type: 'dashed',
                  },
                },
                axisLabel: {
                  color: '#222',
                },
              },
            ],
            series: changeSeriesData(chartData),
            graphic: [
              {
                type: 'image',
                silent: true,
                style: {
                  image: require('@/assets/img/empty.png'),
                  width: 180,
                  height: 120,
                },
                bounding: 'raw',
                top: 'center',
                left: 'center',
                invisible: !isEmpty,
              },
              {
                type: 'text', // 类型：文本
                left: 'center',
                top: 260,
                silent: true, // 不响应事件
                invisible: !isEmpty, // 有数据就隐藏
                style: {
                  fill: '#222',
                  text: intl.formatMessage({
                    id: 'global.noDataYet',
                  }),
                  fontFamily: 'Microsoft YaHei',
                  fontSize: '14px',
                },
              },
            ],
          }}
        />
      </Spin>
    </div>
  );
};
